package com.activiti.spring.controller;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ReceiveTaskController {
	
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	
	@GetMapping("getDeployReceiveTask")
	@ResponseBody
	public Deployment getDeployReceiveTask() {
		Deployment deploy = repositoryService.createDeployment().name("接收任务流程")
				.addClasspathResource("diagrams/ReceiveTask.bpmn").deploy();
		System.out.println("部署id:" + deploy.getId());
		System.out.println("部署名称：" + deploy.getName());
		return deploy;
	}
	
	/**
	 * 1个流程实例id对应n个执行实例id
	 * @param model
	 * @param processKey
	 * @return
	 */
	@GetMapping("getReceiveTaskProcessEngine")
	@ResponseBody
	public String getReceiveTaskProcessEngine(Model model,@RequestParam("processKey") String processKey){
		ProcessInstance pi=runtimeService.startProcessInstanceByKey(processKey);//对应pbmn中的id
		System.out.println("流程实例id:"+pi.getId());
		System.out.println("流程定义id："+pi.getProcessDefinitionId());
		Execution  execution =runtimeService.createExecutionQuery()
		.processInstanceId(pi.getId()).activityId("receivetask1").singleResult();
		
		
		runtimeService.setVariable(execution.getId(),"汇总当日销售额",200000);
		
		//向后执行一步，如果流程处于等待状态，使得流程继续执行
		runtimeService.trigger(execution.getId());
		
		Execution  execution2 =runtimeService.createExecutionQuery()
				.processInstanceId(pi.getId()).activityId("receivetask2").singleResult();
		
		Integer sum=(Integer)runtimeService.getVariable(execution2.getId(),"汇总当日销售额");
		
		System.out.println("给老板发送短信，金额是："+sum);
		
		//向后执行一步，如果流程处于等待状态，使得流程继续执行
				runtimeService.trigger(execution2.getId());
		return "success";
	}
	

}
